﻿var sorter = function (containerId, sorterClass, isNumberSorting) {
    if (!String.prototype.format) {
        String.prototype.format = function () {
            var args = arguments;
            return this.replace(/{(\d+)}/g, function (match, number) {
                return typeof args[number] != 'undefined' ?
                    args[number] : match;
            });
        };
    }

    var SortType = {
        Asc: "ascending",
        Desc: "descending"
    }

    var obj = $("#{0}".format(containerId)),
    sortType = '';
    if (obj.hasClass(SortType.Asc)) {
        sortType = SortType.Desc;
        obj.removeClass(SortType.Asc).addClass(SortType.Desc);
    }
    else if (obj.hasClass(SortType.Desc)) {
        sortType = SortType.Asc;
        obj.removeClass(SortType.Desc).addClass(SortType.Asc);
    }
    else {
        sortType = SortType.Asc;
        obj.addClass(SortType.Asc);
    }

    var elements = obj.children('div').get();
    elements.sort(function (a, b) {
        var new_a = $(".{0}".format(sorterClass), a).text();
        var new_b = $(".{0}".format(sorterClass), b).text();
        var result = 0;
        if (sortType === SortType.Asc) {
            if (isNumberSorting) {
                result = parseInt(new_a, 10) - parseInt(new_b, 10);
            }
            else {
                result = new_a < new_b ? -1 : new_a > new_b ? 1 : 0;
            }
        }
        else {
            if (isNumberSorting) {
                result = parseInt(new_b, 10) - parseInt(new_a, 10);
            }
            else {
                result = new_a > new_b ? -1 : new_a < new_b ? 1 : 0;
            }
        }
        return result;
    });

    for (var i in elements) {
        var element = elements[i];
        obj.append(element);
    }
}